<template>
  <div class="content">
    <div class="block">
      <div class="date_picker">
        <i class="el-range__icon el-icon-date"></i>
        <div
          class="date_item"
          :class="{ date_item_check: dateLabelIndex === 0 }"
          @click="dateLabelIndex = 0"
        >
          本月
        </div>
        <div
          class="date_item"
          :class="{ date_item_check: dateLabelIndex === 1 }"
          @click="dateLabelIndex = 1"
        >
          近两月
        </div>
        <div
          class="date_item"
          :class="{ date_item_check: dateLabelIndex === 2 }"
          @click="dateLabelIndex = 2"
        >
          近三月
        </div>
        <div
          class="date_item"
          :class="{ date_item_check: dateLabelIndex === 3 }"
          @click="dateLabelIndex = 3"
        >
          半年
        </div>
      </div>
      <el-date-picker
        v-if="false"
        v-model="TimeDateValue"
        type="monthrange"
        class="mydatepicker"
        format="yyyy-M-d"
        value-format="yyyy-M-d"
        align="right"
        unlink-panels
        range-separator="-"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        @change="fetchData"
        @focus="showMask = true"
        @blur="showMask = false"
      />
    </div>
    <div class="block">
      <el-row>
        <el-col :span="20">
          <el-input
            v-model="posValue"
            @change="selectImage"
            placeholder="请拾取坐标"
            class="pos_pick_class"
            size="small"
          >
            <!-- <el-button slot="append" icon="location"
             :class="{active:pickFlag==true}"
             @click="beginPick">拾取坐标</el-button> -->
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-tooltip class="item" effect="dark" placement="bottom-start">
            <div slot="content" v-if="northFlag">视角固定</div>
            <div slot="content" v-else>视角跟随</div>
            <el-button
              class="north_btn"
              :class="{ active: northFlag == true }"
              @click="northFlag = !northFlag"
              circle
            >
              <svg-icon icon-class="bei" />
            </el-button>
          </el-tooltip>
        </el-col>
      </el-row>
    </div>
    <move-box
      ref="moveBox"
      :BoxTop="170"
      :BoxRight="20"
      :BoxWidth="780"
      :BoxHeight="650"
      :box-scale="true"
      @closePhoto="closePhoto"
    >
      <div ref="ref_container" class="container">
        <img-box
          ref="imgBox"
          :CanvasWidth="imgBoxSize[0]"
          :CanvasHeight="imgBoxSize[1]"
        ></img-box>
        <div class="line" v-if="imgList.length > 1"></div>
        <div class="timelines" v-if="imgList.length > 1">
          <div
            class="item"
            v-for="(item, index) in imgList"
            :key="index"
            @click="changePhoto(item)"
          >
            <div
              class="slot"
              :class="{ active: curPhotoCode == item.photo_info_code }"
            ></div>
            <div
              class="txt"
              :class="{ active: curPhotoCode == item.photo_info_code }"
            >
              <span>{{ item.photo_time | timeFilter }}</span>
            </div>
          </div>
        </div>
        <!-- 照片信息 -->
        <div class="textBox" v-if="curPhoto">
          <p>图片名称：{{ curPhoto.photo_name }}</p>
          <p>拍摄时间：{{ curPhoto.photo_time }}</p>
        </div>
      </div>
      <div class="img_lists">
        <div class="leftbtn" @click="leftClick">
          <svg-icon icon-class="leftarrow" />
        </div>
        <div class="cards">
          <div
            v-for="(item, index) in clusterImages"
            class="card"
            :key="index"
            :class="[
              { active: pIndex == index },
              { active_click: curClusterIndex == index },
              `list-item-single-${index}`,
            ]"
            @mouseover="selectPhoto(index)"
            @mouseout="outSelect(index)"
            @click="openPhoto(index)"
          >
            <div class="imgbox">
              <el-image
                class="c_img"
                :src="urlAddToken(item.photos_list[0].oss_thumb_url)"
                fit="cover"
              />
              <div class="c_state" v-if="item.photos_list.length > 1">
                {{ item.photos_list.length }}
              </div>
            </div>
          </div>
        </div>
        <div class="rightbtn" @click="rightClick">
          <svg-icon icon-class="rightarrow" />
        </div>
      </div>
    </move-box>
    <div id="heatMap" style="width: 500px; height: 500px" v-show="false"></div>

    <div v-if="showMask" class="full-mask" @click="showMask = false"></div>
  </div>
</template>

<script>
import h337 from "../../../../static/heatMap/heatmap.js";
import { getPhotoHeat, getPhotoHeatRect, getClusterPhoto } from "@/api/kanban";
import MoveBox from "../boxComps/moveBox.vue";
import ImgBox from "../boxComps/imgBox.vue";

import { addUrlToken } from "@/utils/allTool.js";

var heatMap, PhotoTempPLayer;

var MyFrustum = [];
var points, viewPolygon;
var heatMapInstance, heatMapEntity;

export default {
  data() {
    return {
      lastBoxUrl: "",
      lastBoxIndex: 0,
      imgBoxSize: [780, 580],
      maxSize: ["40px", "300px"],
      value1: null,
      value2: null,
      colors: ["#99A9BF", "#F7BA2A", "#ff5500"], // 等同于 { 2: '#99A9BF', 4: { value: '#F7BA2A', excluded: true }, 5: '#FF9900' }
      currentZoom: 10,
      posValue: "",
      pickFlag: false,
      northFlag: false,
      clusterImages: [],
      pIndex: null,
      imgList: [],
      visible: false,
      curClusterIndex: null,
      curPhotoCode: null,
      curPhoto: null,

      pickerOptions: {
        disabledDate(time) {
          const date1 = new Date();
          const date2 = new Date();
          date1.setMonth(date1.getMonth() - 3);
          date2.setMonth(date2.getMonth() + 1);
          var y1 = date1.getFullYear();
          var m1 = date1.getMonth() + 1;

          var y2 = date2.getFullYear();
          var m2 = date2.getMonth() + 1;
          if (m1 < 10) m1 = "0" + m1;
          if (m2 < 10) m2 = "0" + m2;
          var str1 = y1 + "-" + m1 + "-" + "01";
          var str2 = y2 + "-" + m2 + "-" + "01";
          var start = new Date(str1);
          var end = new Date(str2);
          return (
            time.getTime() < start.getTime() - 1000 * 3600 * 24 ||
            time.getTime() > end.getTime()
          );
        },
      },

      // datevalue: '',
      pickHeight: 0, //用于存储点击点的高程
      //
      showMask: false,
      CanvasWidth: 2000, //该参数会对热力图颗粒度产生影响，值越大 覆盖度准确率越高

      deptRectBounds: [],
      // 搜图默认时间独立 不与其它模块同步
      TimeDateValue: [], // [startDate, endDate],
      dateLabelIndex: 0,
    };
  },
  components: {
    MoveBox,
    ImgBox,
  },
  filters: {
    picUrl(url) {
      return url + "?imageMogr2/thumbnail/400x";
    },
    timeFilter(text) {
      var a = text.split(" ");
      a = a[0];
      return a;
    },
  },

  mounted() {
    var that = this;

    // time
    // const nowTimes = Date.now()
    // const oldTimes = nowTimes - (86400000 * 30)
    // const oldDate = this.getDate(oldTimes) // 一个月前的时间
    // const nowDate = this.getDate(nowTimes)// 今天的时间
    // this.datevalue = [oldDate, nowDate]

    getPhotoHeatRect({
      // user_id:120
      dept_id: this.$store.getters.deptId,
    }).then((res) => {
      var bounds = res.data;
      if (bounds) {
        this.deptRectBounds = [
          res.data.min_lon,
          res.data.min_lat,
          res.data.max_lon,
          res.data.max_lat,
        ];
        // 计算长宽比
        var from = turf.point([res.data.min_lon, res.data.min_lat]);
        var to = turf.point([res.data.max_lon, res.data.min_lat]);
        var distance = turf.distance(from, to); //width
        console.log(distance);
        if (distance < 100) {
          this.CanvasWidth = 1000;
        }
        that.initHeatMap();
      }
    });

    // cesium
    if (typeof Cesium !== "undefined") {
      PhotoTempPLayer = new Cesium.PrimitiveCollection();
      viewer.scene.primitives.add(PhotoTempPLayer);
    }
    // 显示拾取按钮
    this.$bus.emit("bottomButtonState", 2);

    // 结束拾取
    this.$bus.on("EndPickFlag", (data) => {
      // this.pickFlag = false
      this.endPick(data);
    });
    // 关闭机巢圈圈图层
    console.log("关闭机巢覆盖区");
    this.$bus.emit("toggleNestLayer", false);
    // 关闭左边窗口
    this.$bus.emit("CloseLeftWindow", false);
    // 修改窗口高度
    console.log(454);
    this.$bus.emit("ChangeRightHeight", "in");

    const tabBar = this.$el.querySelector(".cards");
    tabBar.addEventListener("mousewheel", this.handleScroll);
  },
  created() {},
  methods: {
    urlAddToken(url) {
      return addUrlToken(url);
    },
    handleScroll(e) {
      // 0----down  1----up
      var direction = e.deltaY > 0 ? "0" : "1";
      const tabBar = this.$el.querySelector(".cards");
      //下面的实现的是内部元素横向滚动，前提设置好内部元素横向的滚动样式了
      if (direction === "0") {
        tabBar.scrollLeft += 30;
      } else {
        tabBar.scrollLeft -= 30;
      }
    },
    selectPhoto(index) {
      this.pIndex = index;
      // if(this.curClusterIndex!=index){
      //   MyFrustum[index].update({
      //     color:'rgb(0,255,255)'
      //   })
      // }
    },
    outSelect(index) {
      this.pIndex = null;
      // 判断是否是选中的，是选中的就不改变颜色
      // if(this.curClusterIndex!=index){
      //   MyFrustum[index].update({
      //     color:'rgb(0,255,255)'
      //   })
      // }
    },
    closePhoto() {
      // MyFrustum[this.curClusterIndex].update({
      //   color:'rgb(0,255,255)'
      // })

      CesiumUtil.LayerRemoveAll(TempLayer);
      PhotoTempPLayer.removeAll();
      MyFrustum = [];
      this.curClusterIndex = null;
    },
    leftClick() {
      if (this.curClusterIndex > 0) {
        var index = this.curClusterIndex - 1;
        this.openPhoto(index);
      }
    },
    rightClick() {
      if (this.curClusterIndex < this.clusterImages.length - 1) {
        var index = this.curClusterIndex + 1;
        this.openPhoto(index);
      }
    },
    refreshPhoto(size) {
      this.imgList = this.clusterImages[this.curClusterIndex].photos_list;
      this.$refs.imgBox.SetSize(size);
      this.$refs.imgBox.SetImage(this.lastBoxUrl || this.imgList[0].oss_url);
      document
        .querySelector(`.list-item-single-${this.lastBoxIndex}`)
        .scrollIntoView();
    },
    openPhoto(index) {
      document.querySelector(`.list-item-single-${index}`).scrollIntoView(); // 列表自动滚动到视野中
      console.log(index);

      this.imgList = this.clusterImages[index].photos_list;
      console.log(this.imgList);
      this.$refs.moveBox.toggleShow(true);
      this.$bus.on("closePhoto", (flag) => {
        this.$refs.moveBox.toggleShow(flag);
        this.$bus.off("changeIssueImgScale");
      });
      //
      this.$bus.on("changeIssueImgScale", (flag) => {
        setTimeout(() => {
          const ele = this.$refs.ref_container;
          const width = ele.offsetWidth;
          const height = ele.offsetHeight;
          // this.imgBoxSize = !flag ? [1225, 724] : [780, 580]
          this.imgBoxSize = [width, height];
          setTimeout(() => {
            this.refreshPhoto(this.imgBoxSize);
          }, 20);
        }, 15);
      });
      this.lastBoxUrl = this.imgList[0].oss_url;
      this.lastBoxIndex = index;
      this.$refs.imgBox.SetImage(this.imgList[0].oss_url);

      if (this.curClusterIndex != null) {
        MyFrustum[this.curClusterIndex].update({
          color: "rgb(0,255,255)",
        });
      }

      this.curClusterIndex = index;

      MyFrustum[index].update({
        color: "rgb(255, 255, 0)",
      });

      this.drawViewPolygon(this.imgList[0]);

      this.curPhotoCode = this.imgList[0].photo_info_code;
      this.curPhoto = this.imgList[0];

      // 视角切换
      var arr = this.posValue.split(",");
      var log = arr[0];
      var lat = arr[1];
      var hei = this.pickHeight;

      if (this.northFlag) {
        CesiumUtil.FlyToElementByGPS({
          longitude: log,
          latitude: lat,
          height: hei,
          distance: 1500,
          leftview: true,
        });
      } else {
        var yaw = this.curPhoto["yaw"];
        if (yaw < 0) yaw += 360;
        yaw += 90;
        if (yaw > 360) yaw = yaw - 360;

        var target_p = this.get_another_point(
          this.curPhoto["longitude"],
          this.curPhoto["latitude"],
          yaw,
          200
        );
        console.log(target_p);
        CesiumUtil.FlyToElementByGPS({
          longitude: target_p["lon"],
          latitude: target_p["lat"],
          height: this.curPhoto["exif_xmp"]["absolute_altitude"],
          distance: 1200,
          heading: this.curPhoto["yaw"],
          pitch: this.curPhoto["pitch"],

          // leftview:true
        });
      }
    },
    /**
     *
     * @param {*} lon 经度
     * @param {*} lat 纬度
     * @param {*} angle 角度 (0~360度)
     * @param {*} distance 距离 (米)
     *
     */
    get_another_point(lon, lat, angle, distance) {
      // WGS84坐标系
      var a = 6378137; // 赤道半径
      var b = 6356752.3142; // 短半径
      var f = 1 / 298.257223563; // 扁率

      var alpha1 = angle * (Math.PI / 180);
      var sinAlpha1 = Math.sin(alpha1);
      var cosAlpha1 = Math.cos(alpha1);
      var tanU1 = (1 - f) * Math.tan(lat * (Math.PI / 180));
      var cosU1 = 1 / Math.sqrt(1 + tanU1 * tanU1),
        sinU1 = tanU1 * cosU1;
      var sigma1 = Math.atan2(tanU1, cosAlpha1);
      var sinAlpha = cosU1 * sinAlpha1;
      var cosSqAlpha = 1 - sinAlpha * sinAlpha;
      var uSq = (cosSqAlpha * (a * a - b * b)) / (b * b);
      var A =
        1 + (uSq / 16384) * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
      var B = (uSq / 1024) * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
      var sigma = distance / (b * A),
        sigmaP = 2 * Math.PI;
      while (Math.abs(sigma - sigmaP) > 1e-12) {
        var cos2SigmaM = Math.cos(2 * sigma1 + sigma);
        var sinSigma = Math.sin(sigma);
        var cosSigma = Math.cos(sigma);
        var deltaSigma =
          B *
          sinSigma *
          (cos2SigmaM +
            (B / 4) *
              (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) -
                (B / 6) *
                  cos2SigmaM *
                  (-3 + 4 * sinSigma * sinSigma) *
                  (-3 + 4 * cos2SigmaM * cos2SigmaM)));
        sigmaP = sigma;
        sigma = distance / (b * A) + deltaSigma;
      }

      var tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1;
      var lat2 = Math.atan2(
        sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1,
        (1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp)
      );
      var lambda = Math.atan2(
        sinSigma * sinAlpha1,
        cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1
      );
      var C = (f / 16) * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
      var L =
        lambda -
        (1 - C) *
          f *
          sinAlpha *
          (sigma +
            C *
              sinSigma *
              (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));

      // var revAz = Math.atan2(sinAlpha, -tmp); // final bearing

      return {
        lon: Number(lon) + L * (180 / Math.PI),
        lat: lat2 * (180 / Math.PI),
      };
    },

    changePhoto(item) {
      this.curPhotoCode = item.photo_info_code;
      this.curPhoto = item;
      this.lastBoxUrl = item.oss_url;
      this.$refs.imgBox.SetImage(item.oss_url);
      this.drawViewPolygon(item);
    },
    drawViewPolygon(item) {
      var poly = JSON.parse(item.view_polygon);
      if (poly["type"] == "Polygon") {
        console.log("投影面1", poly.coordinates[0]);
        var arr2 = poly.coordinates[0].reduce(function (a, b) {
          return a.concat(b);
        });
        console.log("投影面2", arr2);
        // 添加投影面
        var polygon = {
          type: "photo_view",
          positions: arr2,
          clamp: true,
          color: "rgba(255, 255, 0, 0.3)",
        };
        if (viewPolygon) {
          TempLayer.entities.remove(viewPolygon);
        }
        viewPolygon = CesiumUtil.AddPolygon(polygon, TempLayer);
      }
    },
    beginPick() {
      this.pickFlag = !this.pickFlag;
      if (this.pickFlag) {
        console.log("222");
        this.$bus.emit("ChangePickFlag", true);
      }
    },
    endPick(data) {
      console.log(data);
      if (data && data.longitude && data.latitude) {
        this.posValue =
          data.longitude.toFixed(7) + "," + data.latitude.toFixed(7);
        this.pickHeight = data.height ? data.height : 0;
        CesiumUtil.LayerRemoveAll(TempLayer);
        let ellipsePosition = Cesium.Cartesian3.fromDegrees(
          data.longitude.toFixed(7),
          data.latitude.toFixed(7),
          data.height + 5 || 5
        );
        var ellipseOption = {
          type: "ellipse_temp",
          longitude: data.longitude.toFixed(7),
          latitude: data.latitude.toFixed(7),
          height: data.height + 5,
          radius: 20,
          color: "rgba(255, 20, 43, 0.2)",
          outline_color: "rgba(255, 41, 91, 0.9)",
        };
        CesiumUtil.drawEllipse(ellipsePosition, TempLayer, ellipseOption);
        this.selectImage();
      }
    },
    fetchData() {
      this.loadHeatMap();
    },
    selectImage() {
      if (this.posValue) {
        var arr = this.posValue.split(",");
        if (arr.length != 2) {
          return false;
        }
        var log = arr[0];
        var lat = arr[1];
        var hei = this.pickHeight;
        getClusterPhoto({
          log: log,
          lat: lat,
          photo_start_time: this.TimeDateValue[0],
          photo_end_time: this.TimeDateValue[1],
          dept_id: this.$store.getters.deptId,
        }).then((res) => {
          PhotoTempPLayer.removeAll();
          this.clusterImages = res.data;
          // 如果没有结果 则关闭图片预览窗口
          if (!res.data) {
            this.$refs.moveBox.toggleShow(false);
          }
          MyFrustum = [];
          if (res.data) {
            for (var i = 0; i < res.data.length; i++) {
              var photo = res.data[i];
              var fru = new CesiumUtil.CreateFrustum(
                {
                  longitude: photo["longitude_g"],
                  latitude: photo["latitude_g"],
                  height:
                    photo["photos_list"][0]["exif_xmp"]["absolute_altitude"],
                  pitch: photo["pitch_g"],
                  heading: photo["yaw_g"],
                  far: 20,
                  id: photo["photos_list"][0]["photo_info_code"],
                },
                PhotoTempPLayer
              );
              MyFrustum.push(fru);
            }
            this.$nextTick(() => {
              var that = this;
              this.curClusterIndex = 0;
              setTimeout(function () {
                that.openPhoto(0);
              }, 200);
            });
          }
        });
      }
    },
    initHeatMap() {
      var mycanvas = document.querySelector("#heatMap");
      mycanvas.style.width = this.CanvasWidth + "px";
      mycanvas.style.height = this.CanvasWidth + "px";
      //创建热力图实例
      heatMapInstance = h337.create({
        container: document.querySelector("#heatMap"),
        radius: 1.5,
        gradient: {
          ".2": "blue",
          ".4": "green",
          ".5": "yellow",
          ".7": "orange",
          ".9": "red",
        },
        maxOpacity: 0.6,
        minOpacity: 0.15,
      });

      // this.loadHeatMap();
    },
    loadHeatMap() {
      getPhotoHeat({
        start_time: this.TimeDateValue[0],
        end_time: this.TimeDateValue[1],
        dept_id: this.$store.getters.deptId,
        // user_id:120
      }).then((res) => {
        if (heatMapEntity) {
          viewer.entities.remove(heatMapEntity);
        }
        if (!res.data) return;
        var dataRaw = res.data;
        /**************方案1**************/
        // 添加数据 最小值，最大值，数据集
        // heatMap.setWGS84Data(0, 100, res.data)
        // 普通权限视角锁定到对应机巢
        var bounds = this.deptRectBounds;

        var canvasWidth = this.CanvasWidth;
        /**************方案2**************/
        var max = 0;
        var points_a = [];
        for (let i = 0; i < dataRaw.length; i++) {
          // 传进原始数据
          let dataItem = dataRaw[i];
          let point = {
            // 将数据点经纬度等比例设置成矩形中的x y坐标 值为原始数据的值
            y: Math.round(
              canvasWidth -
                ((dataItem[1] - bounds[1]) / (bounds[3] - bounds[1])) *
                  (1998.6 / 2000) *
                  canvasWidth
            ),
            x: Math.round(
              ((dataItem[0] - bounds[0]) / (bounds[2] - bounds[0])) *
                (1998.9 / 2000) *
                canvasWidth
            ),
            // x:Math.round((dataItem[0] - bounds[0]) / (bounds[2] - bounds[0]) * canvasWidth),
            // y:Math.round(canvasWidth - (dataItem[1] - bounds[1]) / (bounds[3] - bounds[1]) * canvasWidth),
            value: dataItem[2],
          };
          // 比较设置的最大值和原始数据值大小 取两者间的最大值
          max = Math.max(max, dataItem[2]);
          // 将转换好后的数据存入数组
          points_a.push(point);
        }
        // 设置传入实例的数据
        var data = {
          max: Math.min(max, 100),
          data: points_a,
        };

        // 新建热力图实例并传入设置好的数据
        if (heatMapInstance) {
          heatMapInstance.repaint();
        }
        heatMapInstance.setData(data);

        // 设置画布为生成的热力图
        let canvas = document.getElementsByClassName("heatmap-canvas");
        // canvas[0].width = canvasWidth
        // canvas[0].height = canvasHeight
        // 判断组件是否销毁
        if (this && !this._isDestroyed) {
          // 添加热力图实例
          heatMapEntity = viewer.entities.add({
            name: "heatmap",
            // 设置矩形
            rectangle: {
              // 指定矩形区域
              coordinates: Cesium.Rectangle.fromDegrees(
                bounds[0],
                bounds[1],
                bounds[2],
                bounds[3]
              ),
              // 设置矩形图片为据透明度的热力图
              material: new Cesium.ImageMaterialProperty({
                image: canvas[0],
                transparent: true,
              }),
              // material:Cesium.Color.TAN.withAlpha(0.2)
            },
          });
        }
        /**************方案2结束**************/

        //  加辅助点,用于判断是否准确
        // if(points){
        //   points.removeAll()
        // }

        // points = new Cesium.PointPrimitiveCollection();

        // for(var i=0;i<dataRaw.length;i++){
        //   var p = dataRaw[i]
        //   var alpha = p[2] / data.max;

        //   if(alpha>1.0){
        //     console.log(alpha)
        //   }
        //   alpha = alpha>0.1?alpha:0.1
        //   alpha = alpha<1.0?alpha:1.0

        //   if(alpha<0.15){
        //     var color = Cesium.Color.YELLOW.withAlpha(0.9)
        //   }else{
        //     var color = Cesium.Color.RED.withAlpha(0.9)
        //   }

        //   points.add({
        //     position : Cesium.Cartesian3.fromDegrees(p[0], p[1], 200),
        //     color : color
        //   });
        // }
        // viewer.scene.primitives.add(points)
      });
    },
    onMoveendMap() {
      var height = Math.ceil(viewer.camera.positionCartographic.height);
      var zoom = this.heightToZoom(height);
      var bounds = this.getCurrentExtent();
      console.log(zoom, bounds);

      if (this.currentZoom != zoom) {
        if (zoom < 12 && this.currentZoom >= 12) {
          heatMap.show(true);
          this.currentZoom = zoom;
          // this.loadHeatMap([heatMapBounds.west,heatMapBounds.south,heatMapBounds.east,heatMapBounds.north],400)
        } else if (zoom >= 12 && zoom < 14) {
          heatMap.show(true);
          this.currentZoom = zoom;
          // this.loadHeatMap(bounds,200)
        } else {
          heatMap.show(false);
        }
      }
    },
    getCurrentExtent() {
      var Rectangle = viewer.camera.computeViewRectangle();
      var extent = [
        (Rectangle.west / Math.PI) * 180,
        (Rectangle.south / Math.PI) * 180,
        (Rectangle.east / Math.PI) * 180,
        (Rectangle.north / Math.PI) * 180,
      ];
      return extent;
    },
    heightToZoom(height) {
      var A = 40487.57;
      var B = 0.00007096758;
      var C = 91610.74;
      var D = -40467.74;
      return Math.round(D + (A - D) / (1 + Math.pow(height / C, B)));
    },
    // 格式化时间 返回年月日
    getDate(time) {
      if (time instanceof Date) {
        console.log("updateDateValue 1");
        const valDate = time;
        const Y = valDate.getFullYear();
        const M = valDate.getMonth() + 1;
        const D = valDate.getDate();
        return Y + "-" + M + "-" + D;
      } else if (time) {
        console.log("updateDateValue 2");
        const val = new Date(time);
        const Y = val.getFullYear();
        const M = val.getMonth() + 1;
        const D = val.getDate();
        return Y + "-" + M + "-" + D;
      }
      return "";
    },
    updateDateValue(dateLabelIndex) {
      let startDate = "";
      const endDate = this.getDate(new Date());
      switch (dateLabelIndex) {
        case 0:
          // 本月
          startDate = this.getDateByMonthCount(0);
          break;
        case 1:
          // 近两月
          startDate = this.getDateByMonthCount(2);
          break;
        case 2:
          // 近三月
          startDate = this.getDateByMonthCount(3);
          break;
        case 3:
          // 半年（6个月）
          startDate = this.getDateByMonthCount(6);
          break;
        default:
          break;
      }
      this.TimeDateValue = [startDate, endDate];
      this.fetchData();
    },
    getDateByMonthCount(count) {
      const val = new Date();
      if (count === 0) {
        const Y = val.getFullYear();
        const M = val.getMonth() + 1;
        const D = 1;
        return Y + "-" + M + "-" + D;
      } else if (count > 0 && count < 13) {
        let Y = val.getFullYear();
        let M = val.getMonth() + 1;
        var D = val.getDate();
        if (M > count) {
          M = M - count;
        } else {
          Y = val.getFullYear() - 1;
          M = M + 12 - count;
        }
        if (D > 28 && M == 2) {
          D = 28;
        } else if (D > 30) {
          D = 30;
        }
        return Y + "-" + M + "-" + D;
      } else {
        return "";
      }
    },
  },
  beforeDestroy() {
    console.log("destroy");
    if (heatMap) {
      heatMap.destroy();
      heatMap = null;
      viewer.camera.moveEnd.removeEventListener(this.onMoveendMap);
    }
    this.$bus.off("EndPickFlag");
    this.$bus.emit("toggleNestLayer", true);
    this.$bus.emit("CloseLeftWindow", true);
    this.$bus.emit("ChangeRightHeight", "out");
    this.$bus.emit("PickBtnShow", false);
    viewer.scene.primitives.remove(PhotoTempPLayer);
    CesiumUtil.LayerRemoveAll(TempLayer);

    if (points) {
      points.removeAll();
    }
    if (heatMapEntity) {
      viewer.entities.remove(heatMapEntity);
    }
  },
  watch: {
    dateLabelIndex: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.updateDateValue(newVal);
        }
      },
      immediate: true,
    },
  },
};
</script>

<style lang="scss">
.pos_pick_class {
  margin-top: 10px;
  caret-color: auto;

  .el-input__inner {
    background-color: rgba(183, 178, 178, 0.2);
    color: white;
  }

  .el-input-group__append {
    overflow: hidden;

    .el-button {
      border-color: #033d65;
      background-color: #1876bd;
      color: white;

      &.active {
        background-color: #1c8edf;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
// 时间拾取
@import "@/assets/style/style.scss";

.content {
  padding: 10px;
  color: white;
  text-align: center;
  position: relative;

  .north_btn {
    margin-top: 10px;
    font-size: 16px;
    background-color: rgba(243, 243, 243, 0.3);
    padding: 1px;
    width: 30px;
    height: 30px;

    &.active {
      background-color: rgba(221, 238, 255, 0.9);
    }
  }

  .img_lists {
    width: 100%;
    height: 120px;
    background-color: #17233e;
    display: flex;
    padding: 5px;
    position: absolute;
    bottom: 0;

    .leftbtn,
    .rightbtn {
      width: 50px;
      height: 100%;
      font-size: 40px;
      background-color: rgba(255, 255, 255, 0.66);
      color: rgba(0, 0, 0, 0.7);
      line-height: 120px;
      margin: 0 5px;
      cursor: pointer;

      &:hover {
        background-color: rgba(255, 255, 255, 0.95);
      }
    }

    ::-webkit-scrollbar {
      width: 5px;
      height: 6px;
    }

    ::-webkit-scrollbar-track {
      border-radius: 10px;
      background-color: rgba(0, 0, 0, 0.1);
    }

    ::-webkit-scrollbar-thumb {
      border-radius: 10px;
      -webkit-box-shadow: inset 0 0 6px rgba(255, 255, 255, 0.2);
      background-color: rgba(255, 255, 255, 0.6);
    }

    .cards {
      width: calc(100% - 100px);
      height: 100%;
      overflow-x: auto;
      overflow-y: hidden;
      white-space: nowrap;

      .card {
        width: 160px;
        height: calc(100% - 4px);
        font-size: 13px;
        padding: 0px;
        margin: 0 3px;
        display: inline-block;
        background-color: rgba(243, 243, 243, 0.1);
        cursor: pointer;
        box-sizing: border-box;

        &.active {
          background-color: rgba(215, 241, 243, 0.2);
        }

        &.active_click {
          background-color: rgba(215, 241, 243, 0.2);
          border: 2px solid #ffe861;
        }

        .imgbox {
          width: 100%;
          height: 100%;
          position: relative;

          .c_img {
            height: 100%;
            width: 100%;
            cursor: pointer;
          }

          .c_state {
            position: absolute;
            top: 5px;
            right: 5px;
            height: 16px;
            padding: 0px 4px;
            line-height: 16px;
            font-size: 12px;
            margin-bottom: 2px;
            background-color: #256fb5;
            border-radius: 5px;
            color: #ffffff;
          }
        }
      }
    }
  }

  .container {
    height: calc(100% - 120px);
    width: 100%;
    position: relative;

    .line {
      position: absolute;
      left: vw(20);
      top: 0;
      width: 2px;
      height: 100%;
      z-index: 1;
      background-color: rgba(243, 243, 243, 0.7);
    }

    .timelines {
      position: absolute;
      width: 130px;
      left: 14px;
      top: 0px;
      padding: 0px 10px;
      height: 100%;
      overflow-y: auto;
      // border-left: 2px solid rgba(243,243,243,0.7);
      &:hover {
        background-color: rgba(0, 0, 0, 0.3);
      }

      .item {
        color: white;
        display: flex;
        position: relative;
        padding-top: 20px;
        padding-bottom: 5px;
        cursor: pointer;

        &:hover .slot {
          background-color: rgba(0, 255, 255, 0.9);
        }

        .slot {
          margin-left: 9px;
          width: 14px;
          height: 14px;
          border-radius: 7px;
          background-color: white;
          z-index: 2;
          box-shadow: 0 0 4px rgba(0, 0, 0, 0.8);

          &.active {
            background-color: #ff0000 !important;
            transform: scale(1.3);
          }

          &.hasmark {
            background-color: #ffaa00;
          }
        }

        .txt {
          display: flex;
          flex-direction: column;
          margin-left: 8px;
          text-shadow: 0 0 4px rgba(0, 0, 0, 0.8);

          span {
            font-size: 13px;
            font-weight: 600;
            color: #7ed0ff;
          }

          &.active {
            span {
              color: #ffff7f;
            }
          }
        }
      }
    }

    .textBox {
      position: absolute;
      width: vw(240);
      right: vw(20);
      text-align: right;
      font-size: 13px;
      pointer-events: none;
      bottom: 10px;
      height: auto;
      color: white;
      text-shadow: 0 0 2px rgba(0, 0, 0, 0.3);

      p {
        width: 100%;
        height: 20px;
        margin: 0;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}

.full-mask {
  position: fixed;
  z-index: 20020;
  background-color: rgba(0, 0, 0, 0);
  margin: 0;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  -webkit-transition: opacity 0.3s;
  transition: opacity 0.3s;
  box-sizing: inherit;
}

.date_picker {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 4px 10px;
  width: 100%;
  background: rgba(173, 196, 207, 0.36);
  color: #ffffff;
  border: 1px solid #a3a3a394;
  border-radius: 4px;

  .date_item {
    color: white;
    cursor: pointer;
    font-size: 12px;
    background-color: darkgrey;
    padding: 2px 12px;
    border-radius: 4px;
  }

  .date_item_check {
    color: white;
    cursor: pointer;
    font-size: 12px;
    background-color: dodgerblue;
    padding: 2px 12px;
    border-radius: 4px;
  }
}
</style>
